package com.linsy.product.redis.mq.entity;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.linsy.product.redis.mq.constant.BooleanEnum;
import com.linsy.product.redis.mq.constant.MqStatusEnum;
import com.linsy.product.redis.mq.util.IdBuilder;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

@Data
public class MqDataEntity {

    private Long rowId;

    /**
     * 批次号
     */
    private String batchNo;

    /**
     * 队列Key
     */
    private String mqKey;

    /**
     * 发送数据（JSON字符串）
     */
    private String mqData;

    /**
     * 是否成功消费
     */
    private Integer successIs;

    /**
     * 请求时间（发送到MQ的时间）
     */
    private String sendTime;

    /**
     * 消费开始时间
     */
    private String consumerTime;

    /**
     * 消费结束时间
     */
    private String responseTime;

    /**
     * 重试次数（超过三次算失败）
     */
    private Integer retryTime;

    /**
     * 最大重试次数
     */
    private Integer maxRetryTime;

    /**
     * 执行状态
     * @see MqStatusEnum
     */
    private Integer billStatus;

    /**
     * 最后一次错误信息
     */
    private String lastErrorMsg;

    public static List<MqDataEntity> toEntityList(PutMsgDTO dto) {
        List<Object> list = dto.getValue();
        String key = dto.getKey();
        List<MqDataEntity> entityList = new LinkedList<>();
        String batchNo = IdUtil.fastSimpleUUID();
        LocalDateTime date = LocalDateTime.now();
        Integer waitingStatus = MqStatusEnum.WAITING.getStatus();
        for (Object o : list) {
            MqDataEntity mqDataEntity = new MqDataEntity();
            mqDataEntity.setRowId(IdBuilder.get());
            mqDataEntity.setMqKey(key);
            mqDataEntity.setBatchNo(batchNo);
            mqDataEntity.setMaxRetryTime(10);
            mqDataEntity.setBillStatus(waitingStatus);
            String s = JSON.toJSONString(o);
            if (JSONUtil.isTypeJSON(s)) {
                mqDataEntity.setMqData(s);
            } else {
                mqDataEntity.setMqData(o.toString());
            }
            mqDataEntity.setSendTime(date.format(DatePattern.NORM_DATETIME_FORMATTER));
            entityList.add(mqDataEntity);
        }
        return entityList;
    }

    public void success(LocalDateTime date) {
        this.successIs = BooleanEnum.TRUE;
        this.responseTime = date.format(DatePattern.NORM_DATETIME_FORMATTER);
        this.billStatus = MqStatusEnum.SUCCESS.getStatus();
    }

    public void fail(String message) {
        this.successIs = BooleanEnum.FALSE;
        this.billStatus = MqStatusEnum.FAIL.getStatus();
        this.lastErrorMsg = message.length() > 255 ? message.substring(0, 245) : message;
    }

    public void consume(LocalDateTime date) {
        this.consumerTime = date.format(DatePattern.NORM_DATETIME_FORMATTER);
        this.billStatus = MqStatusEnum.RUNNING.getStatus();
    }
}
